package com.starbaba.apiActivity.view;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.google.gson.JsonObject;
import com.jumai.server.qiniu.QiniuUploadUtils;
import com.opensymphony.xwork2.ModelDriven;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.starbaba.apiActivity.service.ApiModelBasisConfService;
import com.starbaba.common.ResultJson;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.loanActivity.model.UserCommentModel;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.model.utils.JSONUtils;
import com.starbaba.redis.JedisUtils;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiModelItemBasis;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiModelItemOptionBasis;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiModelProject;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiModelType;

@SuppressWarnings({"serial","unchecked","rawtypes","unused"})
public class ApiModelBasisConfAction extends BaseAction implements ModelDriven<ApiModelItemOptionBasis> {

	@SuppressWarnings("deprecation")
    private static BaseDao dao = new BaseDao(Constant.POOL_LIFE);
	
	private static final String COMM_REDIS_KEY = "loan:activity_comment_list_";   //评论列表在redis中key的前缀，跟loan_service中的获取活动评论列表要保持一致
	
	private ApiModelBasisConfService service;
	
	
	@Autowired
	@Qualifier("apiModelBasisConfServiceImpl")
	public void setService(ApiModelBasisConfService service) {
		this.service = service;
	}

	public String show(){
		return "success";
	}
	
	public String addPage() throws AppException{
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String typeSql = "SELECT * FROM loan_api_model_type t";
		String projSql = "SELECT * FROM loan_api_model_project p";
		List<ApiModelType> typeList = dao.list(typeSql, ApiModelType.class);
		List<ApiModelProject> projList = dao.list(projSql, ApiModelProject.class);
		paramsMap.put("typeList", typeList);
		paramsMap.put("projList", projList);
		return "success";
	}
	
	public void saveItem() throws AppException{
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String typeId = (String) paramsMap.get("type_id");
		String projectId = (String) paramsMap.get("project_id");
		String title = (String) paramsMap.get("title");
		String dataKey = (String) paramsMap.get("data_key");
		String remark = (String) paramsMap.get("remark");
		
		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String currTime = dateFormater.format(date);
		
		ApiModelItemBasis item = new ApiModelItemBasis();
		item.setCreate_time(currTime);
		item.setUpdate_time(currTime);
		item.setTitle(title);
		item.setProject_id(Long.valueOf(projectId));
		item.setType_id(Long.valueOf(typeId));
		item.setData_key(dataKey);
		dao.add(item);
		responseSuccess();
	}
	
	public void queryList(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		
		PageResponse pageResponse = new PageResponse();
		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();
		
		List list = service.getDateList(start, length, pageResponse, paramsMap);
		pageResponse.setAaData(list);

		try {
			sendJsonMessage(JsonUtils.toJson(pageResponse));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//获取所属大项列表
	public void getProjList() throws AppException{
		String sql = "SELECT * FROM loan_api_model_project t";
		List<ApiModelProject> projList = dao.list(sql, ApiModelProject.class);
		JsonObject object = new JsonObject();
		String jsonStr = JSONUtils.toJsonString(projList);
		object.addProperty("projList", jsonStr);
		try {
			sendJsonMessage(JsonUtils.toJson(object));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//获取模板类型
	public void getTypeList() throws AppException{
		String sql = "SELECT * FROM loan_api_model_type t";
		List<ApiModelType> typeList = dao.list(sql, ApiModelType.class);
		JsonObject object = new JsonObject();
		String jsonStr = JSONUtils.toJsonString(typeList);
		object.addProperty("typeList", jsonStr);
		try {
			sendJsonMessage(JsonUtils.toJson(object));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void updateProj(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String itemId = (String) paramsMap.get("itemId");
		String projId = (String) paramsMap.get("projId");
		String updateSql = "UPDATE loan_api_model_itembasis SET project_id = ?,update_time = ? WHERE id = ?";
		try {
			dao.update(updateSql, new Object[]{projId,new Date(),itemId});
			responseSuccess();
		} catch (AppException e) {
			e.printStackTrace();
			responseError(e);
		}
	}
	
	public void updateType(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String itemId = (String) paramsMap.get("itemId");
		String typeId = (String) paramsMap.get("typeId");
		String updateSql = "UPDATE loan_api_model_itembasis SET type_id = ?,update_time = ? WHERE id = ?";
		try {
			dao.update(updateSql, new Object[]{typeId,new Date(),itemId});
			responseSuccess();
		} catch (AppException e) {
			e.printStackTrace();
			responseError(e);
		}
	}
	
	public void updateTitle(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String itemId = (String) paramsMap.get("itemId");
		String title = (String) paramsMap.get("title");
		String updateSql = "UPDATE loan_api_model_itembasis SET title = ?,update_time = ? WHERE id = ?";
		try {
			dao.update(updateSql, new Object[]{title,new Date(),itemId});
			responseSuccess();
		} catch (AppException e) {
			e.printStackTrace();
			responseError(e);
		}
	}
	
	public void updateDataKey(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String itemId = (String) paramsMap.get("itemId");
		String dataKey = (String) paramsMap.get("dataKey");
		String updateSql = "UPDATE loan_api_model_itembasis SET data_key = ?,update_time = ? WHERE id = ?";
		try {
			dao.update(updateSql, new Object[]{dataKey,new Date(),itemId});
			responseSuccess();
		} catch (AppException e) {
			e.printStackTrace();
			responseError(e);
		}
	}
	
	//编辑二级项页面
	public String editSecond() throws AppException{
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String itemId = (String) paramsMap.get("itemId");
		String selectSql = "SELECT * FROM loan_api_model_itembasis ib WHERE id = ?";
		String listSql = "SELECT * FROM loan_api_model_item_optionbasis io WHERE io.itembasis_id = ?";
		ApiModelItemBasis item = dao.get(selectSql, ApiModelItemBasis.class, itemId);
		paramsMap.put("item", item);
		List<ApiModelItemOptionBasis> optionList = dao.list(listSql, ApiModelItemOptionBasis.class, itemId);
		paramsMap.put("optionList", optionList);
		paramsMap.put("optionCount", optionList.size());
		return "success";
	}
	
	public void saveOptionList() throws AppException{
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		
		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String currTime = dateFormater.format(date);
		
		Integer index = Integer.valueOf((String) paramsMap.get("index"));
		String itemId = (String) paramsMap.get("itemId");
		if(index != null && index != 0){
			for(int i=1;i<=index;i++){  //循环保存每个option
				String optionId = (String) paramsMap.get("optionId"+i);
				String optionValue = (String) paramsMap.get("optionValue"+i);
				String optionKey = (String) paramsMap.get("optionKey"+i);
				String extraValue = (String) paramsMap.get("extraValue"+i);
				if(optionValue == null || "".equals(optionValue)){
					continue;
				}
				if(optionKey == null || "".equals(optionKey)){
					continue;
				}
				if(extraValue == null || "".equals(extraValue)){
					extraValue = "";
				}
				if(optionId == null || "".equals(optionId)){  //保存
					ApiModelItemOptionBasis option =  new ApiModelItemOptionBasis();
					option.setItembasis_id(Long.valueOf(itemId));
					option.setOption_key(optionKey);
					option.setOption_value(optionValue);
					option.setCreate_time(currTime);
					option.setUpdate_time(currTime);
					option.setExtra_value(extraValue);
					dao.add(option);
				}else{  //更新
					String updateSql = "UPDATE loan_api_model_item_optionbasis SET option_key = ?,option_value = ?,extra_value = ? ,update_time = ? WHERE id = ?";
					dao.update(updateSql, new Object[]{optionKey,optionValue,extraValue,currTime,optionId});
				}
			}
		}
		
		responseSuccess();
	}
	
	public void deleteItem(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String itemId = (String) paramsMap.get("itemId");
		try {
			if(itemId!=null && !"".equals(itemId)){
				String deleteOption = "DELETE FROM loan_api_model_item_optionbasis WHERE itembasis_id = ?";
				String deleteItem = "DELETE FROM loan_api_model_itembasis WHERE id = ?";
				dao.delete(deleteOption, new Object[]{itemId});
				dao.delete(deleteItem, new Object[]{itemId});
				responseSuccess();
			}
		} catch (AppException e) {
			e.printStackTrace();
			responseError(e);
		}
	}
	
	public void deleteOption(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String optionId = (String) paramsMap.get("optionId");
		try {
			if(optionId!=null && !"".equals(optionId)){
				String deleteSql = "DELETE FROM loan_api_model_item_optionbasis WHERE id = ?";
				dao.delete(deleteSql, new Object[]{optionId});
				responseSuccess();
			}
		} catch (AppException e) {
			e.printStackTrace();
			responseError(e);
		}
	}
	
	
	private void responseSuccess() {
		JsonObject result = new JsonObject();
		result.add("result", new ResultJson().toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 *
	 * @Title responseSuccess
	 * @Description <p>
	 *              返回错误信息
	 *              </p>
	 *              　　　　　
	 * @author zhengjunjie
	 * @dateTime 2015年10月16日 下午2:26:53
	 *
	 */
	private void responseError(Exception error) {
		StringWriter writer = new StringWriter();
		error.printStackTrace(new PrintWriter(writer, true));
		ResultJson resultJson = new ResultJson(-2, 0, writer.toString());
		JsonObject result = new JsonObject();
		result.add("result", resultJson.toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			LogService.error(e);
		}
	}

	
	
	
	//删除缓存
	public void deleteCommInRedis(String commentId,String activityId) throws AppException{
		if(activityId == null || "".equals(activityId)){ //如果活动id为空，需要获取活动id
			String selectSql = "SELECT * FROM loan_user_comment c WHERE c.id = ?";
			UserCommentModel comm = dao.get(selectSql, UserCommentModel.class, commentId);
			if(comm == null){
				return;
			}
			activityId = comm.getActivity_id()+"";
		}
		String redisKey = COMM_REDIS_KEY+activityId;
		JedisUtils.del(redisKey);
	}
	
	@Override
	public ApiModelItemOptionBasis getModel() {
		
		return null;
	}

}





